######################################
## quick scan a list of root files
## to check the total number of events
## Lailin, AA, April 2013
######################################

from ROOT import TFile,TTree

input='data12_NTUP_SMWZ_dilep_Lulu.list'
#input='corr.txt'

output='log_'+input
fout=open(output, 'w')

err='err_'+input
ferr=open(err, 'w')

tot_eg, tot_mu, tot=0, 0, 0

list=open(input, 'r')
for files in list.readlines():
  if files[-1]=='\n': file=files[:-1]
  else: file=files
  this_dataset=open(file, 'r')

  this_eg, this_mu=0, 0
  this_temp, temp=0, 0
 
  for this_files in this_dataset.readlines():
    if this_files[-1]=='\n': this_file=this_files[:-1]
    else: this_file=this_files
  
    tf=TFile(this_file)
    # check if file can be opened
    if not tf: 
      print 'Warning ==> Corrupted file: ', this_file
      ferr.write('%s\n' % this_file)
      continue
    # check if file is recoverd from corruption
    if tf.TestBit(TFile.kRecovered): 
      print 'Warning ==> Recovered file: ', this_file
      ferr.write('%s\n' % this_file)
    # check if the tree can be retrieved
    tr=tf.Get("physics")
    if not tr: 
      print 'Warning ==> Corrupted tree: ', this_file
      ferr.write('%s\n' % this_file)
      continue
    temp=tr.GetEntries()
    if 'Egamma' in file: this_eg += temp
    if 'Muons' in file: this_mu += temp
    this_temp += temp
  fout.write('%s    %d\n' % (file, this_temp))
  tot_eg += this_eg
  tot_mu += this_mu
  tot += this_temp

fout.write('tota: %d Egamma: %d Muons: %d\n' % (tot, tot_eg, tot_mu))
